package com.bsj.power.common.def.dto.video;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.BitSet;

/**
 * @Description
 * @Author zhaoyang
 * @Date 2023/6/19 14:35
 */
@Slf4j
public class DataUtil {

    /**
     * 获取GBK格式byte数据
     *
     * @param data
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] getGBKByte(String data) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(data)) {
            return new byte[0];
        }
        return data.getBytes("GBK");
    }


    /**
     * 将BitSet对象转化为ByteArray
     *
     * @param bitSet
     * @return
     */
    public static byte[] bitSet2ByteArray(BitSet bitSet) {
        byte[] bytes = new byte[bitSet.size() / 8];
        for (int i = 0; i < bitSet.size(); i++) {
            int index = i / 8;
            int offset = 7 - i % 8;
            bytes[index] |= (bitSet.get(i) ? 1 : 0) << offset;
        }
        return bytes;
    }

    /**
     * byte[]转int
     *
     * @param bytes
     * @return
     */
    public static int byteArrayToInt(byte[] bytes) {
        int value = 0;
        // 由高位到低位
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            // 往高位游
            value += (bytes[i] & 0x000000FF) << shift;
        }
        return value;
    }

}
